package com.hqyj.servletdemo.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminServlet", value = "/admin")
public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currentSessionId = request.getSession().getId();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("mytoken")) {
                String clientSessionId = cookie.getValue();
                if (currentSessionId.equals(clientSessionId)) {
                    System.out.println("客户端mytoken与服务器一样，登录认证成功！");
                    //response.sendRedirect("WEB-INF/admin/index.jsp");
                    request.getRequestDispatcher("/WEB-INF/admin/index.jsp").forward(request,response);
                    return;
                } else {
                    System.out.println("客户端mytoken与服务器不一致，该token已经过期...");
                    response.sendRedirect("login.jsp");
                    return;
                }
            }
        }
        System.out.println("客户没有mytoken信息");
        response.sendRedirect("login.jsp");
    }
}
